package com.easy.order.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.easy.common.bean.OrderMaster;
import com.easy.common.service.OrderMasterService;
import com.easy.order.mapper.OrderMasterMapper;
import org.apache.dubbo.config.annotation.DubboService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.UUID;

@Service
@DubboService
public class OrderMasterServiceImpl extends ServiceImpl<OrderMasterMapper, OrderMaster> implements OrderMasterService {
    private static final Logger log = LoggerFactory.getLogger(OrderMasterServiceImpl.class);

    @Override
    public OrderMaster getOrderMasterById(Integer id) {
        if (id == null) {
            log.warn("查询总订单失败：ID为空");
            return null;
        }
        // MP自动追加条件：WHERE id=? AND isdel=0
        return super.getById(id);
    }


    @Override
    public OrderMaster getOrderMasterByName(String receiveName) {
        if (receiveName == null || receiveName.trim().isEmpty()) {
            log.warn("查询总订单失败：收货人姓名为空");
            return null;
        }
        QueryWrapper<OrderMaster> queryWrapper = new QueryWrapper<>();
        queryWrapper.like("receive_name", receiveName.trim()) // 总订单表的“收货人姓名”字段
                .eq("isdel", 0); // MP也会自动加，但显式写更清晰
        return baseMapper.selectOne(queryWrapper);
    }


    @Override
    public int addOrderMaster(OrderMaster orderMaster) {
        if (orderMaster == null) {
            log.warn("新增总订单失败：订单对象为空");
            return 0;
        }
        LocalDateTime now = LocalDateTime.now();
        orderMaster.setCreateTime(now);
        orderMaster.setUpdateTime(now);
        // 补充：生成唯一订单号（避免重复）+ 默认未删除
        orderMaster.setOrderNo(System.currentTimeMillis() + "-" + UUID.randomUUID().toString().substring(0, 8));
        orderMaster.setIsdel(0); // 新增默认未删除

        // 校验核心字段（总订单必须有用户ID、收货信息）
        if (orderMaster.getUserId() == null || orderMaster.getReceiveName() == null || orderMaster.getReceivePhone() == null) {
            log.error("新增总订单失败：核心字段（用户ID/收货人/电话）缺失");
            return 0;
        }

        boolean isSuccess = super.save(orderMaster);
        log.info("新增总订单{}：订单号={}", isSuccess ? "成功" : "失败", orderMaster.getOrderNo());
        return isSuccess ? 1 : 0;
    }


    @Override
    public int updateOrderMaster(OrderMaster orderMaster) {
        if (orderMaster.getId() == null) {
            log.warn("更新总订单失败：ID为空");
            return 0;
        }
        // 校验订单是否存在且未删
        if (getOrderMasterById(orderMaster.getId()) == null) {
            log.warn("更新总订单失败：ID={}的订单不存在或已删除", orderMaster.getId());
            return 0;
        }
        orderMaster.setUpdateTime(LocalDateTime.now());
        // MP自动追加条件：UPDATE ... WHERE id=? AND isdel=0
        boolean isSuccess = super.updateById(orderMaster);
        return isSuccess ? 1 : 0;
    }

    @Override
    public int deleteOrderMaster(Integer id) {
        if (id == null) {
            log.warn("软删除总订单失败：ID为空");
            return 0;
        }
        // 校验订单是否存在且未删（避免重复删除）
        if (getOrderMasterById(id) == null) {
            log.warn("软删除总订单失败：ID={}的订单不存在或已删除", id);
            return 0;
        }

        // 核心：MP自动将DELETE转为UPDATE：UPDATE order_master SET isdel=1 WHERE id=? AND isdel=0
        boolean isSuccess = super.removeById(id);
        log.info("软删除总订单{}：ID={}", isSuccess ? "成功" : "失败", id);
        return isSuccess ? 1 : 0;
    }

    @Override
    public List<OrderMaster> getAll(OrderMaster orderMaster) {
        QueryWrapper<OrderMaster> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("isdel", 0); // MP自动加，显式写更清晰

        // 总订单表的有效字段（删除order_id/product_id/seckill_activity_id，这些是子订单的）
        if (orderMaster.getUserId() != null) {
            queryWrapper.eq("user_id", orderMaster.getUserId()); // 按用户ID查
        }
        if (orderMaster.getStatus() != null) {
            queryWrapper.eq("status", orderMaster.getStatus()); // 按订单状态查（0=待支付等）
        }
        if (orderMaster.getOrderNo() != null && !orderMaster.getOrderNo().trim().isEmpty()) {
            queryWrapper.eq("order_no", orderMaster.getOrderNo().trim()); // 按订单号查
        }

        return baseMapper.selectList(queryWrapper);
    }

    @Override
    public IPage<OrderMaster> getPage(OrderMaster orderMaster, IPage<OrderMaster> page) {
        if (page == null) {
            log.warn("分页查询总订单失败：分页参数为空");
            return null;
        }
        QueryWrapper<OrderMaster> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("isdel", 0);

        // 总订单表的分页条件（删除product_name，改用收货人/订单号）
        if (orderMaster.getOrderNo() != null && !orderMaster.getOrderNo().trim().isEmpty()) {
            queryWrapper.like("order_no", orderMaster.getOrderNo().trim()); // 订单号模糊查
        }
        if (orderMaster.getReceiveName() != null && !orderMaster.getReceiveName().trim().isEmpty()) {
            queryWrapper.like("receive_name", orderMaster.getReceiveName().trim()); // 收货人模糊查
        }

        // MP自动分页+过滤已删数据
        return baseMapper.selectPage(page, queryWrapper);
    }
}